//
//  SGSSignInWithEmailViewController.m
//  AgileNYC
//
//  Created by German on 01.08.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSSignInWithEmailViewController.h"
#import "SGSAppDelegate.h"
#import "SGSModelsManager.h"
#import "SGSDelegatesManager.h"
#import "SGSUtils.h"
#import "SGSEventsViewController.h"
#import "SGSDialogsManager.h"
#import "SGSAppConsts.h"
#import "SGSServerManagerConsts.h"

@interface SGSSignInWithEmailViewController () <UITextFieldDelegate>

@property (assign, nonatomic) BOOL isLoginMake;  //We login or create user

@end

@implementation SGSSignInWithEmailViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.edEmail.delegate = self;
    self.edPassword.delegate = self;
    self.edPasswordConfirmation.delegate = self;
    
    self.isLoginMake = YES;
    self.edPasswordConfirmation.alpha = 0.0f;
    
    GSLog(GSLogEvent, @"----- SGSSignInWithEmailViewController Did Load");
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.edEmail becomeFirstResponder];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ([textField isEqual:self.edEmail]) {
        [self.edPassword becomeFirstResponder];
    } else if ([textField isEqual:self.edPassword]) {
        [self.edPassword resignFirstResponder];
    } else if ([textField isEqual:self.edPasswordConfirmation]) {
        [self.edPasswordConfirmation resignFirstResponder];
    }
    
    return YES;
}

#pragma mark - Internal Functions

-(void) showPasswordConfirmationField {
    if (self.edPasswordConfirmation.alpha>0) {
        return;
    }
    
    self.isLoginMake = NO;
    
    [UIView animateWithDuration:0.4f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.edPasswordConfirmation.alpha = 1.0f;
                         self.btnRegister.alpha = 0.0f;
                         self.btnRegister.center = CGPointMake(self.btnRegister.center.x, self.btnRegister.center.y + 40);
                         self.btnLogin.center = CGPointMake(self.edPasswordConfirmation.center.x, self.btnLogin.center.y + 40);
                     }
                     completion:^(BOOL finished){
                         
                     }];
    if ([[self.edEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        [self.edEmail becomeFirstResponder];
        return;
    }
    
    if ([self.edPassword.text length]==0) {
        [self.edPassword becomeFirstResponder];
        return;
    }
    
    [self.edPasswordConfirmation becomeFirstResponder];
}

-(void) hidePasswordConfirmationField {
    [self.edPasswordConfirmation resignFirstResponder];
    
    self.isLoginMake = YES;
    
    [UIView animateWithDuration:0.4f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.edPasswordConfirmation.alpha = 0.0f;
                         self.btnRegister.alpha = 1.0f;
                         self.btnRegister.center = CGPointMake(self.btnRegister.center.x, self.btnRegister.center.y - 40);
                         self.btnLogin.center = CGPointMake(self.edPasswordConfirmation.frame.origin.x + (self.btnLogin.frame.size.width/2), self.btnLogin.center.y - 40);
                     }
                     completion:^(BOOL finished){
                         
                     }];

    [self.edEmail becomeFirstResponder];
}

-(BOOL) checkPasswordEqual {
    if ([self.edPassword.text isEqualToString:self.edPasswordConfirmation.text]) {
        return YES;
    } else {
        return NO;
    }
}

-(BOOL) checkEmailAndPasswordEmpty {
    
    BOOL emailIsNotEmpty = ([[self.edPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>0);
    
    BOOL passwordIsNotEmpty = ([self.edPassword.text length]>0);
    
    return emailIsNotEmpty & passwordIsNotEmpty;
}


#pragma mark - Actions

- (IBAction)onForgotMyPasswordButtonClick:(id)sender {
    
}

- (IBAction)onSignInButtonClick:(UIButton *)sender {
    
    if (![self checkEmailAndPasswordEmpty]) {
        GSLog(GSLogError, @"Email or Password are empty");
        
        [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:Email_And_Password_Is_Empty_Message onComplete:nil];

        return;
    }
    
    
    [self.edEmail resignFirstResponder];
    [self.edPassword resignFirstResponder];
    [self.edPasswordConfirmation resignFirstResponder];
    
    SGSAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    GSUser * loginUser = modelsManager.currentUser;
    
    if (self.isLoginMake) { //Login only, not create user
        
        [self startSpinner];
        
        [modelsManager loginUserWithEmail:self.edEmail.text password:self.edPassword.text onComplete:^(BOOL result, NSString * errorString) {
            [appDelegate stopSpinner];
            
            if (result) {

                SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
                
                [self.navigationController popToViewController:delegatesManager.currentEventsVC animated:YES];

            } else {
                if (!errorString) { //It means that user has not registred yet
                    [self showPasswordConfirmationField];
                    self.isLoginMake = NO;
                } else {
                    [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:errorString onComplete:nil];
                }
            }
            
        }];
    } else { //Create, not login user (creation will be completed in profile viewcontroller)
        if ([self checkPasswordEqual]) {
            
            [self startSpinner];
            
            [[SGSModelsManager sharedModelsManager] checkUserEmail:self.edEmail.text
                onComplete:^(BOOL result, NSString * errorString) {
                    [self stopSpinner];
                    if (result) {
                        [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:errorString onComplete:nil];
                    } else {
                        loginUser.socialType = GSEmailLoginType;
                        loginUser.eMail = self.edEmail.text;
                        loginUser.password = self.edPassword.text;
                        loginUser.isRegistered = [NSNumber numberWithBool:NO];
                        loginUser.isSynchronized = [NSNumber numberWithBool:YES];
                        
                        SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
                        
                        delegatesManager.currentProfileVC.isNewUser = YES;
                        delegatesManager.controllerToBeOpened = delegatesManager.currentProfileVC;
                        
                        [self.navigationController popToViewController:delegatesManager.currentEventsVC animated:YES];
                    }
                }];
        } else {
            GSLog(GSLogError, @"Passwords are not equal");
            
            [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:Passwords_Are_Not_Equal_Message onComplete:nil];

            self.edPassword.text = @"";
            self.edPasswordConfirmation.text = @"";

        }
        
        [self hidePasswordConfirmationField];
        self.isLoginMake = YES;
        
    }
}

- (IBAction)onRegisterButtonClick:(id)sender { // Login button
    [self startSpinner];
    if([self.edEmail.text length]>0) {
        [[SGSModelsManager sharedModelsManager] checkUserEmail:self.edEmail.text
            onComplete:^(BOOL result, NSString * errorString) {
                [self stopSpinner];
                if (result) {
                    [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:errorString onComplete:nil];
                } else {
                   [self showPasswordConfirmationField];
                }
            }];
    } else {
        [self stopSpinner];
        [self showPasswordConfirmationField];
    }
    
   
}

- (IBAction)onBackButtonClick:(id)sender {
    GSLog(GSLogWarning, @"Login canceled");
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - Spinner

-(void) startSpinner {
    //return;
    
    SGSAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate startSpinner];
    
}

-(void) stopSpinner {
    SGSAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate stopSpinner];
}

#pragma mark - System Functions

- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}

@end
